package com.syn.vr.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.documentfile.provider.DocumentFile;

import com.gaoyi.basemodule.baseUtil.ActivityUtil;
import com.gaoyi.basemodule.baseUtil.AppUtil;
import com.gaoyi.basemodule.baseUtil.PermissionUtils;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseUtil.ToastUtil;
import com.gaoyi.basemodule.baseUtil.WindowUtil;
import com.gaoyi.basemodule.baseact.BaseViewActivity;
import com.gaoyi.basemodule.basebean.Event;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.gaoyi.basemodule.basedialog.LoadingDialogUtils;
import com.syn.vr.R;
import com.syn.vr.constant.RequestCode;
import com.syn.vr.control.ClearCacheDialog;
import com.syn.vr.databinding.ActivitySettingBinding;
import com.syn.vr.util.FileUtil;

import java.util.Map;

public class SettingActivity extends BaseViewActivity<ActivitySettingBinding> {

    private ActivityResultLauncher<Intent> mChoiceTreeIntent;

    @Override
    protected void initData() {
        WindowUtil.setWindowDecorView(this);
        mChoiceTreeIntent = registerForActivityResult(RequestCode.REQUEST_DOCUMENT);
        Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "Oswald-Bold.ttf");
        mBinding.tvMainTitle.setTypeface(typeface);
        mBinding.ivClose.setOnClickListener(view -> finish());
        mBinding.tvLanguage.setOnClickListener(view -> startActivity(new Intent(this, LanguageActivity.class)));
        mBinding.tvExportDb.setOnClickListener(view -> exportDb());
        mBinding.tvAbout.setOnClickListener(view -> startActivity(new Intent(this, AboutUsActivity.class)));
        mBinding.btnLogout.setOnClickListener(view -> {
            new ClearCacheDialog(mContext, getString(R.string.confirm_logout), getString(R.string.cancel), getString(R.string.confirm), v -> {
                SPUtil.getInstance().putString(SPName.TOKEN, "");
                SPUtil.getInstance().putInt(SPName.REFRESH_TOKEN, 0);
                ActivityUtil.getInstance().logout();
                Intent intent = new Intent(AppUtil.getContext(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                AppUtil.getContext().startActivity(intent);
            }).show(getSupportFragmentManager());
        });
    }

    private void exportDb() {
        if (PermissionUtils.addPermission(this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE}, mPermissionsResult)) {
            try {
                ToastUtil.showToast(R.string.p_sel_tree);
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                mChoiceTreeIntent.launch(intent);
            } catch (Exception e) {
                ToastUtil.showToast(R.string.open_file_error);
            }
        } else {
            ToastUtil.showToast(R.string.p_allow_permission);
        }
    }

    @Override
    protected ActivitySettingBinding getViewBinding() {
        return ActivitySettingBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void event(Event event) {

    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {

    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {
        if (requestCode == RequestCode.REQUEST_DOCUMENT) {
            int resultCode = result.getResultCode();
            if (resultCode != Activity.RESULT_OK) {
                ToastUtil.showToast(R.string.sel_tree_empty);
                return;
            }
            if (result.getData() == null || result.getData().getData() == null) {
                ToastUtil.showToast(R.string.sel_tree_error);
                return;
            }

            final DocumentFile documentFile = DocumentFile.fromTreeUri(mContext, result.getData().getData());
            if (documentFile == null) {
                ToastUtil.showToast(R.string.sel_tree_error);
                return;
            }
            LoadingDialogUtils.getInstance().showLoading(this, getString(R.string.exporting));
            new Thread(() -> FileUtil.copyDBToSD(mContext, mHandler, documentFile)).start();
        }
    }

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                // 導出數據庫成功
                case FileUtil.BACKUP_SUCCESS:
                    LoadingDialogUtils.getInstance().dismiss();
                    ToastUtil.showToast(R.string.export_success);
                    break;
                // 導出數據庫失敗
                case FileUtil.BACKUP_FAIL:
                    LoadingDialogUtils.getInstance().dismiss();
                    ToastUtil.showToast(R.string.export_error);
                    break;
                // 沒有數據庫可以導出
                case FileUtil.BACKUP_EMPTY:
                    LoadingDialogUtils.getInstance().dismiss();
                    ToastUtil.showToast(R.string.export_empty);
                    break;
            }
        }
    };
}